package cn.com.bsoft.cloud;

import cn.com.bsoft.cloud.entity.company.PTCompanyMess;
import cn.com.bsoft.cloud.service.CloudCompanyService;
import cn.com.bsoft.cloud.utils.AesUtils;
import cn.com.bsoft.cloud.utils.test.RSAUtils;
import groovy.util.logging.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.nio.charset.Charset;

// 注入spring容器
@Component
// 定义filterName 和过滤的url
@WebFilter(filterName = "my2Filter" ,urlPatterns = "/api/test/queryTestDrugList")
@Slf4j
public class My2Filter implements Filter {

    private  String prkey ="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKaaxCPCpNELAdqBrSRvx6N7Xig/8icsMPT+vn7dJ/bJRgM+UlxomNSdw7zBPzAaYpxMCKeQZQ7ueViD72nUa7tH+Y7jH2PNosGTYkVv9sm8xbodVQTJbpOSWHeMLQYkHByUrEzLJG/taBWYm0vznTNcVKWGNa/SXTWD+oub3gP9AgMBAAECgYAXkh3d0VPwH1aLy3zrgsUD5BhWKXXhBOeIQeJBoJhe2esF2nNcj4/PxOJEejKuY40//6HZ0xv5GNQiKchdeKglA7QMLXrJ2N5GhXQb05XCNZoEvP7cL19Kb9bnSQRuWyXFoo89n6ZjpJPv/55Uzk8Kwp3FNvWWxtLQOmUlsmOLIQJBAPO/vu5bCT1WRuDP+bSr3/K6SRtCUy7V4Bpk2gaoOr4c3HPnj0dHzFMZYhoDbfevhCyUptdVtwxdFOM1IvKkJt8CQQCu+mxMCw3RO+4dZ6FxCH0+jXmmTvYgIgnbT4aNXihmi7Vn+mi6TvbK6aHyYWiRlDLJBq5fgGSpdoucbQ3kYzyjAkEAjR+fM/GRT+n77316XZiFeMtSOG4WKy+5KI7rjJ8qI5giKxkOY362VgaEPftuV9FO/WCzmEkQSiA6T7IcIc/YkQJAOC+JXtGd2jXYO/Du0hDbxp4/Fbv9JExJxfY/Sl2Vs3fhBEZQIqMAdB+ZNO86WKSxugM/MsNTj2bVZaFO+Ks06QJBAOoWA30cLjUGL7SphMfjiCMtJ4gWA/9hk+gkZEYQ2Pk3e78/E+MWfquK/hnIkhTFniU5tdXCil2r9RCbANb3i38=";

    @Autowired
    private CloudCompanyService cloudCompanyService;

    private byte[] encodedData;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext sc = filterConfig.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null && cxt.getBean(CloudCompanyService.class) != null && cloudCompanyService == null) {
            cloudCompanyService =cxt.getBean(CloudCompanyService.class);
        }
        logger.info("TestFilter init");


    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        ServletRequest requestWrapper = null;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String header = request.getHeader("companyCode");
        WrapperResponse wrapResponse = new WrapperResponse((HttpServletResponse)servletResponse);

        if(header == null ) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        PTCompanyMess companyMess = cloudCompanyService.getCompanyMess(header);
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) servletRequest,companyMess);
        }
        if(companyMess == null || requestWrapper ==null){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        filterChain.doFilter(requestWrapper, wrapResponse);
        String data = wrapResponse.getContent();
        byte[] aesData = AesUtils.encrypt(data,companyMess.getSecret());
        try {
            encodedData = RSAUtils.encryptByPrivateKey(aesData,prkey);
        }catch (Exception e){
            encodedData="".getBytes(Charset.forName("UTF-8"));
        }

        String  encodeString = Base64.encodeBase64String(encodedData);
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        StringBuilder sb= new StringBuilder();
        sb.append(encodeString);
        byte[] bytes =sb.toString().getBytes("UTF-8");
        httpServletResponse.getOutputStream().write(bytes);
        httpServletResponse.setContentLength(bytes.length);
        httpServletResponse.flushBuffer();
    }
    @Override
    public void destroy() {

    }



}
